<template>
  <view class="bg-white h-screen flex flex-col">
    <!-- 顶部状态栏 -->
    <view class="px-6 pt-12 pb-4 flex items-center justify-between border-b border-gray-100">
      <view class="flex items-center">
        <view class="text-blue-500 mr-3" @click="goBack">
          <text class="fas fa-chevron-left"></text>
        </view>
        <view>
          <text class="text-xl font-bold">灯光控制</text>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="flex-1 px-6 py-4 overflow-auto">
      <!-- 灯光开关 -->
      <view class="flex justify-between items-center mb-6">
        <text class="text-lg font-medium">灯光</text>
        <label class="relative inline-flex items-center cursor-pointer">
          <input type="checkbox" v-model="lightEnabled" class="sr-only peer" @change="updateLightSettings">
          <view class="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-500"></view>
        </label>
      </view>

      <!-- 灯光模式 -->
      <view class="mb-8">
        <text class="text-lg font-medium mb-3 block">灯光模式</text>
        <view class="grid grid-cols-2 gap-3">
          <view 
            class="p-4 border rounded-xl flex items-center space-x-3" 
            :class="[lightMode === 'white' ? 'bg-blue-50 border-blue-200' : 'border-gray-200']"
            @click="setLightMode('white')"
          >
            <view class="w-8 h-8 rounded-full bg-white border border-gray-200 flex items-center justify-center">
              <text class="fas fa-lightbulb text-yellow-400"></text>
            </view>
            <text class="font-medium">白光模式</text>
          </view>
          
          <view 
            class="p-4 border rounded-xl flex items-center space-x-3"
            :class="[lightMode === 'color' ? 'bg-blue-50 border-blue-200' : 'border-gray-200']"
            @click="setLightMode('color')"
          >
            <view class="w-8 h-8 rounded-full bg-gradient-to-r from-red-500 via-green-500 to-blue-500 flex items-center justify-center">
              <text class="fas fa-palette text-white"></text>
            </view>
            <text class="font-medium">彩光模式</text>
          </view>
          
          <view 
            class="p-4 border rounded-xl flex items-center space-x-3"
            :class="[lightMode === 'gradient' ? 'bg-blue-50 border-blue-200' : 'border-gray-200']"
            @click="setLightMode('gradient')"
          >
            <view class="w-8 h-8 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 flex items-center justify-center">
              <text class="fas fa-sliders-h text-white"></text>
            </view>
            <text class="font-medium">渐变模式</text>
          </view>
          
          <view 
            class="p-4 border rounded-xl flex items-center space-x-3"
            :class="[lightMode === 'rhythm' ? 'bg-blue-50 border-blue-200' : 'border-gray-200']"
            @click="setLightMode('rhythm')"
          >
            <view class="w-8 h-8 rounded-full bg-gradient-to-r from-blue-500 to-green-500 flex items-center justify-center">
              <text class="fas fa-music text-white"></text>
            </view>
            <text class="font-medium">律动模式</text>
          </view>
        </view>
      </view>
      
      <!-- 颜色选择器（仅在彩光模式下显示） -->
      <view v-if="lightMode === 'color'" class="mb-8">
        <text class="text-lg font-medium mb-3 block">颜色</text>
        <view class="color-picker mb-4" @click="handleColorPickerClick">
          <view class="color-picker-inner"></view>
          <view class="color-picker-overlay"></view>
          <view 
            class="color-picker-handle" 
            :style="{ left: colorPosition.x + '%', top: colorPosition.y + '%', backgroundColor: currentColor }"
          ></view>
        </view>
        
        <!-- 预设颜色 -->
        <view class="flex justify-between mt-4">
          <view class="w-10 h-10 rounded-full bg-red-500" @click="setColor('#ef4444')"></view>
          <view class="w-10 h-10 rounded-full bg-yellow-500" @click="setColor('#eab308')"></view>
          <view class="w-10 h-10 rounded-full bg-green-500" @click="setColor('#10b981')"></view>
          <view class="w-10 h-10 rounded-full bg-blue-500" @click="setColor('#3b82f6')"></view>
          <view class="w-10 h-10 rounded-full bg-purple-500" @click="setColor('#8b5cf6')"></view>
          <view class="w-10 h-10 rounded-full bg-white border border-gray-200" @click="setColor('#ffffff')"></view>
        </view>
      </view>

      <!-- 亮度控制 -->
      <view class="mb-8">
        <view class="flex justify-between items-center mb-3">
          <text class="text-lg font-medium">亮度</text>
          <text class="text-sm text-gray-500">{{ brightness }}%</text>
        </view>
        <slider 
          :value="brightness" 
          min="0" 
          max="100" 
          @change="onBrightnessChange" 
          activeColor="#3b82f6"
          backgroundColor="#e5e7eb"
          block-size="20"
        />
        <view class="flex justify-between mt-2 text-xs text-gray-400">
          <text>0%</text>
          <text>100%</text>
        </view>
      </view>
      
      <!-- 速度控制（仅在律动或渐变模式下显示） -->
      <view v-if="lightMode === 'rhythm' || lightMode === 'gradient'" class="mb-8">
        <view class="flex justify-between items-center mb-3">
          <text class="text-lg font-medium">变化速度</text>
          <text class="text-sm text-gray-500">{{ speed }}%</text>
        </view>
        <slider 
          :value="speed" 
          min="0" 
          max="200" 
          @change="onSpeedChange" 
          activeColor="#3b82f6"
          backgroundColor="#e5e7eb"
          block-size="20"
        />
        <view class="flex justify-between mt-2 text-xs text-gray-400">
          <text>0%</text>
          <text>200%</text>
        </view>
      </view>

      <!-- 保存按钮 -->
      <button 
        class="w-full py-4 rounded-xl bg-blue-500 text-white font-medium hover:bg-blue-600 transition-colors"
        @click="saveLightSettings"
      >
        保存设置
      </button>
    </view>
  </view>
</template>

<script>
import { deviceApi } from '@/api/index.js'

export default {
  data() {
    return {
      deviceId: '',
      lightEnabled: true,
      lightMode: 'white', // white, color, gradient, rhythm
      currentColor: '#3b82f6',
      colorPosition: { x: 50, y: 50 },
      brightness: 75,
      speed: 100,
      loading: false
    }
  },
  
  onLoad(options) {
    this.deviceId = options.deviceId || ''
    this.loadLightSettings()
  },
  
  methods: {
    async loadLightSettings() {
      if (!this.deviceId) return
      
      this.loading = true
      try {
        const result = await deviceApi.getDeviceDetail(this.deviceId)
        
        if (result && result.errCode === 0) {
          const deviceInfo = result.data
          if (deviceInfo.lightSettings) {
            this.lightEnabled = deviceInfo.lightSettings.enabled
            this.brightness = deviceInfo.lightSettings.brightness || 75
            this.lightMode = deviceInfo.lightSettings.mode || 'white'
            
            if (deviceInfo.lightSettings.color) {
              this.currentColor = deviceInfo.lightSettings.color
            }
            
            if (deviceInfo.lightSettings.speed) {
              this.speed = deviceInfo.lightSettings.speed
            }
          }
        } else {
          uni.showToast({
            title: result?.errMsg || '获取灯光设置失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载灯光设置失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    setLightMode(mode) {
      this.lightMode = mode
    },
    
    handleColorPickerClick(e) {
      // 获取颜色选择器的位置和尺寸
      const picker = e.target
      const rect = picker.getBoundingClientRect()
      
      // 计算点击位置相对于选择器的百分比
      const x = (e.clientX - rect.left) / rect.width * 100
      const y = (e.clientY - rect.top) / rect.height * 100
      
      // 限制在选择器范围内
      this.colorPosition = {
        x: Math.max(0, Math.min(100, x)),
        y: Math.max(0, Math.min(100, y))
      }
      
      // 根据位置计算颜色（简化版）
      const hue = this.colorPosition.x / 100 * 360
      const lightness = 50 - (this.colorPosition.y / 100 * 50)
      this.currentColor = `hsl(${hue}, 100%, ${lightness}%)`
    },
    
    setColor(color) {
      this.currentColor = color
    },
    
    onBrightnessChange(e) {
      this.brightness = e.detail.value
    },
    
    onSpeedChange(e) {
      this.speed = e.detail.value
    },
    
    async updateLightSettings() {
      // 实时更新灯光状态
      if (!this.deviceId) return
      
      try {
        await deviceApi.updateDevice(this.deviceId, {
          lightSettings: {
            enabled: this.lightEnabled
          }
        })
      } catch (error) {
        console.error('更新灯光状态失败:', error)
      }
    },
    
    async saveLightSettings() {
      if (!this.deviceId) return
      
      this.loading = true
      try {
        const result = await deviceApi.updateDevice(this.deviceId, {
          lightSettings: {
            enabled: this.lightEnabled,
            brightness: this.brightness,
            mode: this.lightMode,
            color: this.currentColor,
            speed: this.speed
          }
        })
        
        if (result && result.errCode === 0) {
          uni.showToast({
            title: '灯光设置已保存',
            icon: 'success'
          })
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: result?.errMsg || '保存灯光设置失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('保存灯光设置失败:', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 工具类样式 */
.bg-white { background-color: #ffffff; }
.bg-gray-200 { background-color: #e5e7eb; }
.bg-blue-50 { background-color: #eff6ff; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-blue-600 { background-color: #2563eb; }
.bg-red-500 { background-color: #ef4444; }
.bg-yellow-500 { background-color: #eab308; }
.bg-green-500 { background-color: #10b981; }
.bg-purple-500 { background-color: #8b5cf6; }

.from-red-500 { --tw-gradient-from: #ef4444; }
.via-green-500 { --tw-gradient-via: #10b981; }
.to-blue-500 { --tw-gradient-to: #3b82f6; }
.from-purple-500 { --tw-gradient-from: #8b5cf6; }
.to-pink-500 { --tw-gradient-to: #ec4899; }
.from-blue-500 { --tw-gradient-from: #3b82f6; }
.to-green-500 { --tw-gradient-to: #10b981; }

.text-white { color: #ffffff; }
.text-blue-500 { color: #3b82f6; }
.text-gray-200 { color: #e5e7eb; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-yellow-400 { color: #facc15; }

.text-xs { font-size: 24rpx; }
.text-sm { font-size: 28rpx; }
.text-lg { font-size: 36rpx; }
.text-xl { font-size: 40rpx; }

.font-medium { font-weight: 500; }
.font-bold { font-weight: 700; }

.h-screen { height: 100vh; }
.h-5 { height: 40rpx; }
.h-6 { height: 48rpx; }
.h-8 { height: 64rpx; }
.h-10 { height: 80rpx; }
.w-5 { width: 40rpx; }
.w-8 { width: 64rpx; }
.w-10 { width: 80rpx; }
.w-11 { width: 88rpx; }
.w-full { width: 100%; }

.flex { display: flex; }
.grid { display: grid; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }
.items-center { align-items: center; }
.justify-between { justify-content: space-between; }
.justify-center { justify-content: center; }
.space-x-3 > * + * { margin-left: 24rpx; }

.p-4 { padding: 32rpx; }
.px-6 { padding-left: 48rpx; padding-right: 48rpx; }
.py-4 { padding-top: 32rpx; padding-bottom: 32rpx; }
.pt-12 { padding-top: 96rpx; }
.pb-4 { padding-bottom: 32rpx; }
.mb-3 { margin-bottom: 24rpx; }
.mb-4 { margin-bottom: 32rpx; }
.mb-6 { margin-bottom: 48rpx; }
.mb-8 { margin-bottom: 64rpx; }
.mr-3 { margin-right: 24rpx; }
.mt-2 { margin-top: 16rpx; }
.mt-4 { margin-top: 32rpx; }
.block { display: block; }

.border { border-width: 2rpx; }
.border-b { border-bottom-width: 2rpx; }
.border-gray-100 { border-color: #f3f4f6; }
.border-gray-200 { border-color: #e5e7eb; }
.border-gray-300 { border-color: #d1d5db; }
.border-blue-200 { border-color: #bfdbfe; }

.rounded-xl { border-radius: 24rpx; }
.rounded-full { border-radius: 50%; }

.overflow-auto { overflow: auto; }
.transition-colors { transition-property: color, background-color, border-color; transition-duration: 200ms; }
.transition-all { transition-property: all; transition-duration: 200ms; }

.grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.gap-3 { gap: 24rpx; }

.relative { position: relative; }
.absolute { position: absolute; }
.inset-0 { top: 0; right: 0; bottom: 0; left: 0; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; }

.hover\:bg-blue-600:hover { background-color: #2563eb; }

.after\:content-[''] { content: ''; }
.after\:absolute { position: absolute; }
.after\:top-\[2px\] { top: 2px; }
.after\:left-\[2px\] { left: 2px; }
.after\:bg-white { background-color: #ffffff; }
.after\:border-gray-300 { border-color: #d1d5db; }
.after\:border { border-width: 2rpx; }
.after\:rounded-full { border-radius: 50%; }
.after\:h-5 { height: 40rpx; }
.after\:w-5 { width: 40rpx; }
.after\:transition-all { transition-property: all; transition-duration: 200ms; }

.peer:checked ~ .peer-checked\:after\:translate-x-full { transform: translateX(100%); }
.peer:checked ~ .peer-checked\:after\:border-white { border-color: #ffffff; }
.peer:checked ~ .peer-checked\:bg-blue-500 { background-color: #3b82f6; }
.peer-focus\:outline-none { outline: 2px solid transparent; outline-offset: 2px; }

.bg-gradient-to-r { background-image: linear-gradient(to right, var(--tw-gradient-stops)); }
.from-red-500.via-green-500.to-blue-500 { --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-via), var(--tw-gradient-to); }

/* 颜色选择器样式 */
.color-picker {
  position: relative;
  width: 100%;
  height: 400rpx;
  border-radius: 24rpx;
  overflow: hidden;
}
.color-picker-inner {
  position: absolute;
  inset: 0;
  background: linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
}
.color-picker-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(0,0,0,1) 100%);
}
.color-picker-handle {
  position: absolute;
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  border: 4rpx solid white;
  box-shadow: 0 0 0 2rpx rgba(0,0,0,0.3);
  transform: translate(-50%, -50%);
}

/* Font Awesome 图标样式 */
.fas {
  font-family: "Font Awesome 5 Free", "Font Awesome 5 Brands";
  font-weight: 900;
}
.fa-chevron-left:before { content: "\f053"; }
.fa-lightbulb:before { content: "\f0eb"; }
.fa-palette:before { content: "\f53f"; }
.fa-sliders-h:before { content: "\f1de"; }
.fa-music:before { content: "\f001"; }
</style>
